package com.rdxer.myblog.service;

import com.rdxer.myblog.config.JwtConfiguration;
import com.rdxer.myblog.model.Account;
import com.rdxer.myblog.repository.AccountRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class AuthService {
    @Autowired
    AccountRepository accountRepository;

    // 能执行完就能登陆
    // 报错
    public String login(String username,String password)  {
        List<Account> allByUsername = accountRepository.findAllByUsername(username);
        if (allByUsername == null || allByUsername.size() == 0){
            // 不需要捕获
            throw new RuntimeException("没有此用户");
            // 需要捕获 和 处理的
            // throw new Exception("没有此用户");
        }

        Account account = allByUsername.get(0);

        if (!Objects.equals(account.getPassword(),password)) {
            throw new RuntimeException("密码不正确");
        }
        // 成功登陆

        long expiration = 60 * 60 * 24 * 1000;

        String token = Jwts.builder()
                .setSubject(account.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, Base64.getEncoder().encodeToString(JwtConfiguration.secret.getBytes(StandardCharsets.UTF_8)))
                .compact();

        return token;
    }

    public void register(String username, String displayName, String password) {
        List<Account> allByUsername = accountRepository.findAllByUsername(username);
        if (allByUsername != null && allByUsername.size() > 0){
            throw new RuntimeException("此用户已存在");
        }
        Account account = new Account();
        account.setUsername(username);
        account.setDisplayName(displayName);
        // TODO
        account.setPassword(password);

        //
        account.setId(UUID.randomUUID().toString());
        account.setCreateDate(System.currentTimeMillis());
        account.setRole("user");
        account.setDisable(false);

        accountRepository.save(account);
    }

    public Account userinfo(String token) {
        var jwt = Jwts.parser()
                .setSigningKey(Base64.getEncoder().encodeToString(JwtConfiguration.secret.getBytes(StandardCharsets.UTF_8)))
                .parseClaimsJws(token);
        Claims body = jwt.getBody();
        String username =  body.getSubject();
        List<Account> allByUsername = accountRepository.findAllByUsername(username);

        if (allByUsername == null || allByUsername.size() == 0){
            throw new RuntimeException("没有此用户");
        }

        return allByUsername.get(0);
    }
}
